package net.zjitc.servlet.login;

import net.zjitc.domain.User;
import net.zjitc.service.UserService;
import net.zjitc.service.impl.UserSerivceImpl;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

//注解(servlet的名字是唯一的，一个url对应一个servlet)
@WebServlet(name = "loginServlet",urlPatterns = "/login")
public class LoginServlet extends HttpServlet {
    UserService userService = new UserSerivceImpl();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       //拿到请示的参数
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        User user = userService.findByUsernameAndPassword(username, password);
        //resp.setStatus(404);
        resp.setHeader("Content-Type","text/html;charset=UTF-8");
        PrintWriter writer = resp.getWriter();
        //web服务：iso-8859-1
        //响应头可以设置 很多的参数：可以设置编码方式
        if (user!=null){
            //我们将用户信息放入session: 通过request对象
            HttpSession session = req.getSession();
            session.setAttribute("user",username);
           // writer.write("<h1>登录成功</h1>");
            //任务请示转发给/goodslist处理
            RequestDispatcher dispatcher = req.getRequestDispatcher("/goodsList");
            dispatcher.forward(req,resp);

        }else {
            //System.out.println("用户名或密码错误");
            writer.write("用户名或密码错误");
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getMethod();
        String agent = req.getHeader("User-Agent");
        System.out.println("agent="+agent);
        doGet(req,resp);
    }
}
